/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityLifecycleCallbacks;
import ohos.aafwk.ability.AbilityPackage;
import ohos.utils.PacMap;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.annotations.VisibleForTesting;

import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;

import io.sentry.Breadcrumb;
import io.sentry.IHub;
import io.sentry.ITransaction;
import io.sentry.Integration;
import io.sentry.Scope;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.SpanStatus;
import io.sentry.util.Objects;

/**
 * AbilityLifecycleIntegration
 *
 * @since 2021-06-01
 */
public final class AbilityLifecycleIntegration
    implements Integration, Closeable, AbilityLifecycleCallbacks {
    private final @NotNull AbilityPackage abilityPackage;
    private IHub hub;
    private SentryOhosOptions options;

    private boolean isPerformanceEnabled = false;

    // WeakHashMap isn't thread safe but AbilityLifecycleCallbacks is only called from the
    // main-thread
    private final @NotNull WeakHashMap<Ability, ITransaction> activitiesWithOngoingTransactions =
        new WeakHashMap<>();

    /**
     * AbilityLifecycleIntegration
     *
     * @param abilityPackage AbilityPackage
     * @param buildInfoProvider IBuildInfoProvider
     */
    public AbilityLifecycleIntegration(
        final @NotNull AbilityPackage abilityPackage, final @NotNull IBuildInfoProvider buildInfoProvider) {
        this.abilityPackage = abilityPackage;
        Objects.requireNonNull(buildInfoProvider, "BuildInfoProvider is required");
    }

    @Override
    public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) {
        this.options =
            Objects.requireNonNull(
                (options instanceof SentryOhosOptions) ? (SentryOhosOptions) options : null,
                "SentryOhosOptions is required");

        this.hub = Objects.requireNonNull(hub, "Hub is required");

        this.options
            .getLogger()
            .log(
                SentryLevel.DEBUG,
                "AbilityLifecycleIntegration enabled: %s",
                this.options.isEnableAbilityLifecycleBreadcrumbs());

        isPerformanceEnabled = isPerformanceEnabled(this.options);

        if (this.options.isEnableAbilityLifecycleBreadcrumbs() || isPerformanceEnabled) {
            abilityPackage.registerCallbacks(this, null);
            this.options.getLogger().log(SentryLevel.DEBUG, "AbilityLifecycleIntegration installed.");
        }
    }

    private boolean isPerformanceEnabled(final @NotNull SentryOhosOptions options) {
        return options.isTracingEnabled() && options.isEnableAutoAbilityLifecycleTracing();
    }

    @Override
    public void close() throws IOException {
        abilityPackage.unregisterCallbacks(this, null);
        if (options != null) {
            options.getLogger().log(SentryLevel.DEBUG, "AbilityLifecycleIntegration removed.");
        }
    }

    private void addBreadcrumb(final Ability ability, final @NotNull String state) {
        if (options != null && hub != null && options.isEnableAbilityLifecycleBreadcrumbs()) {
            final Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setType("navigation");
            breadcrumb.setData("state", state);
            breadcrumb.setData("screen", getAbilityName(ability));
            breadcrumb.setCategory("ui.lifecycle");
            breadcrumb.setLevel(SentryLevel.INFO);
            hub.addBreadcrumb(breadcrumb);
        }
    }

    private @NotNull String getAbilityName(final Ability ability) {
        return ability.getClass().getSimpleName();
    }

    private void stopPreviousTransactions() {
        for (final Map.Entry<Ability, ITransaction> entry
            : activitiesWithOngoingTransactions.entrySet()) {
            final ITransaction transaction = entry.getValue();
            finishTransaction(transaction);
        }
    }

    private void startTracing(final Ability ability) {
        if (isPerformanceEnabled && !isRunningTransaction(ability) && hub != null) {
            // as we allow (a) single transaction running on the bound Scope, we finish the previous ones
            stopPreviousTransactions();

            // we can only bind to the scope if there's no running transaction
            final ITransaction transaction =
                hub.startTransaction(getAbilityName(ability), "navigation");

            // lets bind to the scope so other integrations can pick it up
            hub.configureScope(
                scope -> {
                    applyScope(scope, transaction);
                });

            activitiesWithOngoingTransactions.put(ability, transaction);
        }
    }

    /**
     * applyScope
     *
     * @param scope Scope
     * @param transaction ITransaction
     */
    @VisibleForTesting
    public void applyScope(final @NotNull Scope scope, final @NotNull ITransaction transaction) {
        scope.withTransaction(
            scopeTransaction -> {
                // we'd not like to overwrite existent transactions bound to the Scope
                // manually.
                if (scopeTransaction == null) {
                    scope.setTransaction(transaction);
                } else if (options != null) {
                    options
                        .getLogger()
                        .log(
                            SentryLevel.DEBUG,
                            "Transaction '%s' won't be bound to the Scope since there's one already in there.",
                            transaction.getName());
                }
            });
    }

    private boolean isRunningTransaction(final Ability ability) {
        return activitiesWithOngoingTransactions.containsKey(ability);
    }

    private void stopTracing(final Ability ability, final boolean shouldFinishTracing) {
        if (isPerformanceEnabled && shouldFinishTracing) {
            final ITransaction transaction = activitiesWithOngoingTransactions.get(ability);
            finishTransaction(transaction);
        }
    }

    private void finishTransaction(final ITransaction transaction) {
        if (transaction != null) {
            SpanStatus status = transaction.getStatus();

            // status might be set by other integrations, let's not overwrite it
            if (status == null) {
                status = SpanStatus.OK;
            }
            transaction.finish(status);
        }
    }

    @TestOnly
    @NotNull
    public WeakHashMap<Ability, ITransaction> getActivitiesWithOngoingTransactions() {
        return activitiesWithOngoingTransactions;
    }

    @Override
    public void onAbilityStart(Ability ability) {
        startTracing(ability);
        addBreadcrumb(ability, "started");
    }

    @Override
    public void onAbilityActive(Ability ability) {
        addBreadcrumb(ability, "active");

        if (options != null) {
            stopTracing(ability, options.isEnableAbilityLifecycleTracingAutoFinish());
        }
    }

    @Override
    public void onAbilityInactive(Ability ability) {
        addBreadcrumb(ability, "inactive");
    }

    @Override
    public void onAbilityForeground(Ability ability) {
        addBreadcrumb(ability, "foreground");
    }

    @Override
    public void onAbilityBackground(Ability ability) {
        addBreadcrumb(ability, "background");
    }

    @Override
    public void onAbilityStop(Ability ability) {
        addBreadcrumb(ability, "stopped");
        stopTracing(ability, true);
        if (isPerformanceEnabled) {
            activitiesWithOngoingTransactions.remove(ability);
        }
    }

    @Override
    public void onAbilitySaveState(PacMap pacMap) {
    }
}
